package com.mall.service.impl;

import com.mall.common.utils.Security;
import com.mall.controller.vo.CartVO;
import com.mall.dao.custom.CtCartMapper;
import com.mall.entity.Cart;
import com.mall.service.CartService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author xyl
 * @date 2021-03-03 17:42
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CtCartMapper cartMapper;


    @Override
    public int add(Cart cart) {
        Cart temp = cartMapper.selectByGoodsIdAndUserId(cart.getGoodsId(),Security.getCurrentUserId());
        //购物车不存在此商品 , 则添加 , 否则数量添加
        if(ObjectUtils.isEmpty(temp)){
            cart.setCreateBy(Security.getCurrentUserId());
            cart.setCreateTime(new Date());
            cart.setTotal(cart.getCount() * cart.getPrice());
            return cartMapper.insert(cart);
        }else{
            temp.setCount(temp.getCount() + cart.getCount());
            temp.setUpdateTime(new Date());
            temp.setUpdateBy(Security.getCurrentUserId());
            temp.setTotal(temp.getCount() * temp.getPrice());
            return cartMapper.updateByPrimaryKey(temp);
        }
    }

    @Override
    public int remove(Integer carId) {
        return cartMapper.deleteByPrimaryKey(carId);
    }

    @Override
    public List<CartVO> listVO() {
        return cartMapper.selectCartVO(Security.getCurrentUserId());
    }

    @Override
    public int removeByGoodsId(Integer goodsId) {
        return cartMapper.deleteByGoodsIdAndUserId(goodsId,Security.getCurrentUserId());
    }

    @Override
    public Cart getByGoodsIdAndUserId(Integer goodsId, Integer currentUserId) {
        return cartMapper.selectByGoodsIdAndUserId(goodsId,currentUserId);
    }

}
